<template>
    <el-drawer v-model="drawer" :modal="modal" :showClose="showClose" :direction="direction" :size="getSize"
        :before-close="handleClose" :modalClass="['userInfo-modal', userInfoType != 'userInfo' && 'account-modal']">
        <template #header>
            <template v-if="userInfoType == 'userInfo'">
                <div class="userInfo-title">{{ $t('message.userInfo.title') }}</div>
            </template>
            <template v-if="userInfoType != 'userInfo'">
                <div class="account-title">
                    <svg class="back" @click="backUserInfo()">
                        <use xlink:href="#keowledge-fanhuishangyiji"></use>
                    </svg>
                    <div class="line"></div>
                    <div class="userInfo-title">{{ $t('message.userInfo.accountSet') }}</div>
                </div>
            </template>
            <svg class="userInfo-close" v-if="!showClose" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </template>
        <template #default>
            <div class="user-info-body" v-if="userInfoType == 'userInfo'">
                <div class="user-info-box">
                    <div class="user-info-bg"></div>
                    <img :src="userStore.userInfo.headImg ? userStore.userInfo.headImg : userImg" class="header-img">
                    <div class="info">
                        <div class="user-tenant-name" v-tooltip-auto-show>
                            <el-tooltip effect="light" :content="userStore.tenantInfo.shortName" placement="bottom">
                                <span> {{ userStore.tenantInfo.shortName }}</span>
                            </el-tooltip>
                        </div>
                        <div class="user-name" v-tooltip-auto-show>
                            <el-tooltip effect="light" :content="userStore.userInfo.realName" placement="bottom">
                                <span>{{ userStore.userInfo.realName }}</span>
                            </el-tooltip>
                        </div>
                    </div>
                </div>
                <div class="seeting-logout-box">
                    <div class="setting-button button" @click="handleSetting()">
                        <span>{{ $t('message.userInfo.accountSet') }}</span>
                        <svg class="userInfo-close">
                            <use xlink:href="#keowledge-zhanghushezhi"></use>
                        </svg>
                    </div>
                    <div class="logout-button button" @click="handleLogout()">
                        <span>{{ $t('message.userInfo.exitLogin') }}</span>
                        <svg class="userInfo-close">
                            <use xlink:href="#keowledge-tuichudenglu"></use>
                        </svg>
                    </div>
                </div>
                <div class="tenant-box">
                    <div class="tenant-title">{{ $t('message.userInfo.switchTenant') }}</div>
                    <div class="tenant-body">
                        <div class="tenant-lists">
                            <el-scrollbar max-height="calc(100vh - 336px)">
                                <div class="tenant-item" v-for="(item, index) in tenantsList" :key="index"
                                    :class="[item.id == userStore.userInfo.tenantId && 'active']"
                                    @click="changeTenant(item)">
                                    <img class="tenant-img" :src="item.icon">
                                    <div class="tenant-name" v-tooltip-auto-show>
                                        <el-tooltip effect="light" placement="bottom" :content="item.shortName">
                                            <span>{{ item.shortName }}</span>
                                        </el-tooltip>
                                    </div>
                                    <div class="tenant-check">
                                        <svg class="check-icon" v-if="item.id == userStore.userInfo.tenantId">
                                            <use xlink:href="#keowledge-xuanzhong"></use>
                                        </svg>
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                    </div>
                </div>
            </div>
            <div class="account-set-body" v-if="userInfoType != 'userInfo'">
                <div class="account-menu-box">
                    <div class="menu-item" v-for="(item, index) in accountMenuList" :key="index"
                        @click="changeMenu(item)" :class="[currentMenu == item.value && 'menu-item-active']">
                        <svg class="icon">
                            <use v-bind:xlink:href="`#${currentMenu == item.value ? item.iconActive : item.icon}`"></use>
                        </svg>
                        <span>{{ $t(item.lable) }}</span>
                    </div>
                </div>
                <div class="menu-item-info-box">
                    <div class="user-box" v-if="currentMenu == 'user'">
                        <div class="user-title">{{ $t('message.userInfo.personInfo') }}</div>
                        <div class="user-item">
                            <div class="user-item-name">{{ $t('message.userInfo.avatar') }}</div>
                            <div class="user-item-content">
                                <el-upload ref="headImgUpload" class="avatar-uploader"
                                    action="/mgr/jvs-auth/upload/jvs-public" list-type="picture"
                                    accept=".jpg,.jpeg,.png" :data="paramData" :limit="1" :file-list="imgFileList"
                                    :show-file-list="false" :on-remove="headImgRemove" :headers="headers"
                                    :on-success="headImgSuccessHandle" :on-error="headImgErrHandle">
                                    <img v-if="userdata.headImg" :src="userdata.headImg" class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </div>
                        </div>
                        <div class="user-item">
                            <div class="user-item-name">{{ $t('message.userInfo.nickName') }}</div>
                            <div class="user-item-content">
                                <el-input ref="editName" v-if="editNameShow" v-model="userdata.realName" size="mini"
                                    @blur="realNameEdit" maxlength="10"></el-input>
                                <template v-else>
                                    <span>{{ userdata.realName }}</span>
                                    <svg class="edit-name-icon" @click="editRealName">
                                        <use xlink:href="#keowledge-bianji"></use>
                                    </svg>
                                </template>
                            </div>
                        </div>
                        <div class="user-item" v-for="(item, index) in userList" :key="index">
                            <div class="user-item-name">{{ $t(item.label) }}</div>
                            <div class="user-item-content">
                                {{ userdata[item.props] || '--' }}
                            </div>
                        </div>
                        <el-button class="submit-button" type="primary"
                            @click="saveUserInfo">{{ $t('message.buttons.saveInfo') }}</el-button>
                    </div>
                    <div class="account-box" v-if="currentMenu == 'account'">
                        <div class="user-title">{{ $t('message.userInfo.accountManager') }}</div>
                        <div class="s-title">{{ $t('message.userInfo.bindAccount') }}</div>
                        <div class="bind phone-box">
                            <div class="title">{{ $t('message.userInfo.bindAccount') }}</div>
                            <div class="bind-input">
                                <el-input :placeholder="$t('message.placeholder.pleasePhone')" v-model="phoneYzm.value"
                                    :readonly="!!phoneYzm.phone" @input="bindInputChange('phone')"></el-input>
                                <el-button type="primary" @click="bindOrNext('phone')"
                                    :class="[phoneYzm.phone && 'unbind']" v-if="phoneYzm.step == 1"
                                    :disabled="!phoneYzm.phone && !isMobile(phoneYzm.value)">{{ phoneYzm.phone ? $t('message.buttons.bind') : $t('message.buttons.nextStep') }}</el-button>
                            </div>
                            <div class="bind-input" v-if="phoneYzm.step == 2 && phoneYzm.value">
                                <el-input :placeholder="$t('message.placeholder.pleaseYzm')"
                                    v-model="phoneYzm.yzm"></el-input>
                                <el-button class="send-button" @click="sendYzm('phone')">{{ phoneYzm.text }}</el-button>
                            </div>
                            <div class="buttons-box" v-if="phoneYzm.step == 2 && phoneYzm.value">
                                <el-button type="primary" :disabled="!phoneYzm.yzm"
                                    @click="bindPhoneOrEmail('phone')">{{ $t('message.bind.bind') }}</el-button>
                                <el-button class="cancal"
                                    @click="cancalUnBind('phone')">{{ $t('message.buttons.cancal') }}</el-button>
                            </div>
                        </div>
                        <div class="bind email-box">
                            <div class="title">{{ $t('message.userInfo.bindEmail') }}</div>
                            <div class="bind-input">
                                <el-input :placeholder="$t('message.placeholder.pleaseEmail')" v-model="emailYzm.value"
                                    :readonly="!!emailYzm.email" @input="bindInputChange('email')"></el-input>
                                <el-button type="primary" :class="[emailYzm.email && 'unbind']"
                                    @click="bindOrNext('email')" v-if="emailYzm.step == 1"
                                    :disabled="!phoneYzm.email && !isEmail(emailYzm.value)">{{ emailYzm.email ? $t('message.buttons.bind') : $t('message.buttons.nextStep') }}</el-button>
                            </div>
                            <div class="bind-input" v-if="emailYzm.step == 2 && emailYzm.value">
                                <el-input :placeholder="$t('message.placeholder.pleaseYzm')"
                                    v-model="emailYzm.yzm"></el-input>
                                <el-button class="send-button" @click="sendYzm('email')">{{ emailYzm.text }}</el-button>
                            </div>
                            <div class="buttons-box" v-if="emailYzm.step == 2 && emailYzm.value">
                                <el-button type="primary" :disabled="!emailYzm.yzm"
                                    @click="bindPhoneOrEmail('email')">{{ $t('message.bind.bind') }}</el-button>
                                <el-button class="cancal"
                                    @click="cancalUnBind('email')">{{ $t('message.buttons.cancal') }}</el-button>
                            </div>
                        </div>
                        <div class="s-title">{{ $t('message.userInfo.bindThirdAccount') }}</div>
                        <div class="other-bind">
                            <div class="other-item" v-for="(item, index) in otherList" :key="index">
                                <svg class="other-icon">
                                    <use v-bind:xlink:href="`#${item.icon}`"></use>
                                </svg>
                                <span class="label">{{ $t(item.label) }}</span>
                                <el-button :class="[exceptions[item.props] && 'binding']"
                                    @click="bindStatusChange(item)">{{ exceptions[item.props] ? $t('message.buttons.unbind') : $t('message.buttons.bind') }}</el-button>
                            </div>
                        </div>
                    </div>
                    <div class="password-box" v-if="currentMenu == 'password'">
                        <div class="user-title">{{ $t('message.userInfo.setPassword') }}</div>
                        <div class="tips">{{ $t('message.userInfo.setLoginPassowrd') }}</div>
                        <el-input class="pwd-input" :placeholder="$t('message.placeholder.pleasePassword')"
                            type="password" v-model="pwd"></el-input>
                        <el-input class="pwd-input" :placeholder="$t('message.placeholder.pleaseRePassword')"
                            type="password" v-model="pwds"></el-input>
                        <div class="buttons-box">
                            <el-button type="primary" :disabled="!(pwd && pwds)"
                                @click="submitPwd()">{{ $t('message.buttons.submit') }}</el-button>
                            <el-button class="cancal" @click="cancalPwd()">{{ $t('message.buttons.cancal') }}</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </el-drawer>
    <el-dialog v-model="bindVisible" width="475px" :show-close="false" :close-on-click-modal="false"
        :class="['bind-dialog', bindItem.props == 'LDAP' && 'LDAP-dialog']">
        <template #header>
            <div class="bind-title">{{ $t('message.buttons.bind') }}{{ bindItem.label }}</div>
            <svg class="userInfo-close" @click="handleBindClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </template>
        <template #default>
            <div class="bind-body">
                <div class="qcode-box">
                    <div class="qcode-tips" v-if="bindItem.props != 'LDAP'">
                        {{ $t('message.login.pleaseUse') }}{{ bindItem.props == 'WECHAT_MP' ? $t('message.login.weChat') : bindItem.props == 'Ding' ? $t('message.login.dingTalk') : $t('message.login.weCom') }}{{ $t('message.login.scan') }}{{ loginType == 'wxmp' ? $t('message.login.followOfficalAccount') : '' }}
                    </div>
                    <div class="qcode-body-box" v-if="bindItem.props != 'LDAP'">
                        <img id="weixinCode" @click="freshWeixin" :src="OfficQrcodeUrl"
                            v-if="bindItem.props == 'WECHAT_MP' && OfficQrcodeUrl" scrolling="no" frameborder="0">
                        <div class="qcode-mark" v-if="loginType == 'wxmp' && isExpires" @click="freshWeixin">
                            <div class="tips">{{ $t('message.login.qrExpired') }}</div>
                        </div>
                        <div class="iframe-box" v-if="hasLoginRight(bindItem.props, ['Ding', 'WX_ENTERPRISE'])">
                            <!-- 钉钉扫码登录 -->
                            <iframe id="ddLogin" class="dd-box" v-if="bindItem.props == 'Ding' && ddCodeUrl"
                                :src="ddCodeUrl" scrolling="no" frameborder="0"></iframe>
                            <!-- 企业微信扫码登录 -->
                            <iframe id="wxenterpriseCode" class="wxenter-box" v-if="bindItem.props == 'WX_ENTERPRISE'"
                                :src="`/auth/just/login/WECHAT_ENTERPRISE?client_id=${client_id}&url=` + callbackUrl"
                                scrolling="no" frameborder="0"></iframe>
                        </div>
                    </div>
                    <div class="ldap-box" v-else>
                        <el-form ref="ldapFormRef" :model="ldapForm" :rules="ldapRules" label-position="top">
                            <el-form-item :label="$t('message.account')" prop="account">
                                <el-input v-model="ldapForm.account"
                                    :placeholder="$t('message.placeholder.pleaseLDAPAccount')" />
                            </el-form-item>
                            <el-form-item :label="$t('message.password')" prop="password">
                                <el-input v-model="ldapForm.password"
                                    :placeholder="$t('message.placeholder.pleaseLDAPPassword')" type="password" />
                            </el-form-item>
                        </el-form>

                    </div>
                </div>
            </div>
        </template>
        <template #footer v-if="bindItem.props == 'LDAP'">
            <div class="button-box">
                <el-button class="cancal" @click="handleBindClose">{{ $t('message.buttons.cancal') }}</el-button>
                <el-button type="primary" @click="bindLADP(ldapFormRef)">{{ $t('message.buttons.bind') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    computed,
    getCurrentInstance,
    nextTick
} from 'vue'
import useUserInfoStore from '@/store/userInfo';
import useKnowledgeStore from '@/store/knowledge'
import userImg from '@/assets/common/user.png'
import { useRouter, useRoute } from "vue-router"
import { isMobile, isEmail } from '@/utils/validate'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const userStore = useUserInfoStore()
const knowStore = useKnowledgeStore()
const router = useRouter();
const route = useRoute();
import {
    getUserInfo, updateAccountHead, editUser, setPassWord, bindWX, bindLDAP, unbindLDAP, unbindWX, unbindQW, unbindDD, unbindPhone, unbindEmail,
    sendPhoneCode, sendEmailCode, bindEmail, bindPhone
} from '@/api/user'
import { getOffLoginQcode, checkQrcodeState, getInfoByLoginType } from '@/api/login'
import { enCodePasswordKey } from "@/const/const"
import { encryption } from "@/utils/util";
import { removeItemAll } from '@/utils/store'
import { enCodeKey, client_id } from "@/const/const"
import type { FormInstance, FormRules } from 'element-plus'
const { proxy } = getCurrentInstance()
const props = defineProps({
    direction: {
        type: String,
        default: 'rtl'
    },
    remove: Function,
    hasModal: {
        type: Boolean,
        default: true
    },
    modalTrans: {
        type: Boolean,
        default: true
    },
    showClose: {
        type: Boolean,
        default: false
    },
    width: {
        type: [Number, String],
        default: '360px'
    }
})
const { drawer, editNameShow, pwd, pwds, exceptions, phoneYzm, emailYzm, imgFileList, headers, OfficQrcodeUrl, isExpires, QRcodeUUId } = toRefs(
    reactive({
        //定义数组和对象
        exceptions: {},
        drawer: true,
        editNameShow: false,
        pwd: '',
        pwds: '',
        OfficQrcodeUrl: '',
        isExpires: false,
        QRcodeUUId: '',
        phoneYzm: {
            step: 1,
            text: $t('message.login.getVeriCode'),
            phone: '',
            value: '',
            yzm: '',
            time: 180,
            disabled: false
        },
        emailYzm: {
            step: 1,
            text: $t('message.login.getVeriCode'),
            email: '',
            value: '',
            yzm: '',
            time: 180,
            disabled: false
        },
        imgFileList: [],
        headers: {
            businessId: userStore.userInfo.id,
            tenantId: userStore.userInfo.tenantId,
            Authorization: ('Bearer ' + userStore.access_token)
        }
    })
);
let userdata = ref({
    realName: '',
    exceptions: {},
    headImg: '',
    phone: '',
    email: ""
})
const paramData = reactive({
    module: '/jvs-knowledge-ui/userImage/'
})
const editName = ref()
const headImgUpload = ref()
const userInfoType = ref('userInfo')
const currentMenu = ref('user')
const accountMenuList = ref([
    {
        lable: 'message.userInfo.personInfo',
        value: 'user',
        icon: 'keowledge-a-gerenxinxi-xuanzhong1',
        iconActive: 'keowledge-gerenxinxi-xuanzhong'
    }, {
        lable: 'message.userInfo.accountManagers',
        value: 'account',
        icon: 'keowledge-zhanghuguanli-weixuanzhong',
        iconActive: 'keowledge-zhanghuguanli-xuanzhong'
    }, {
        lable: 'message.userInfo.setPassword',
        value: 'password',
        icon: 'keowledge-shezhimima-weixuanzhong',
        iconActive: 'keowledge-shezhimima-xuanzhong'
    }
])
const userList = ref([
    {
        label: 'message.typeMenu.rolePermission',
        props: ''
    },
    {
        label: 'message.typeMenu.department',
        props: 'deptName'
    },
    {
        label: 'message.typeMenu.employeeNo',
        props: 'employeeNo'
    },
    {
        label: 'message.typeMenu.level',
        props: 'level'
    },
    {
        label: 'message.typeMenu.position',
        props: 'jobName'
    }
])
const otherList = ref([
    {
        icon: 'keowledge-weixin-2',
        label: 'message.login.weChat',
        props: "WECHAT_MP"
    }, {
        icon: 'keowledge-qiyeweixin',
        label: 'message.login.weCom',
        props: "WX_ENTERPRISE"
    }, {
        icon: 'keowledge-dingding',
        label: 'message.login.dingTalk',
        props: "Ding"
    }, {
        icon: 'keowledge-LADP',
        label: 'message.login.LDAP',
        props: "LDAP"
    }
])
const bindVisible = ref(false)
const callbackUrl = ref(`${location.origin}'/%23/login/callback?back=bind'`)
const ddCodeUrl = ref('')
const ddInfo = ref({
    appId: ''
})
let bindItem = reactive({
    icon: '',
    label: '',
    props: ""
})
const QRCheckSetInterval = ref(null)
const phoneYzmInterval = ref(null)
const emailYzmInterval = ref(null)
const ldapFormRef = ref<FormInstance>()
const ldapForm = reactive({
    account: '',
    passowrd: ''
})
const ldapRules = reactive<FormRules>({
    account: [{ required: true, message: $t('message.placeholder.pleaseAccount'), trigger: "blur" }],
    password: [{ required: true, message: $t('message.placeholder.pleasePassword'), trigger: "blur" }]
})

const modal = computed(() => {
    return props.hasModal
})
const tenantsList = computed(() => {
    return userStore.userInfo.tenants
})
const getSize = computed(() => {
    if (userInfoType.value == 'userInfo') {
        return props.width
    } else {
        return '800px'
    }
})
// 监听钉钉扫码
if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', dingdingBackHandle, false);
} else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onmessage', dingdingBackHandle);
}

function handleClose() {
    if (userInfoType.value != 'userInfo') {
        backUserInfo()
    }
    userInfoType.value = 'userInfo'
    drawer.value = false
    if (props.remove) props.remove()
}
function backUserInfo() {
    resetYzm()
    currentMenu.value = 'user'
    userInfoType.value = 'userInfo'
}
function handleSetting(flag = false) {
    getUserInfo().then(res => {
        if (res.data.code == 0) {
            userdata.value = res.data.data
            phoneYzm.value.phone = userdata.value.phone
            phoneYzm.value.value = userdata.value.phone
            emailYzm.value.email = userdata.value.email
            emailYzm.value.value = userdata.value.email
            exceptions.value = userdata.value.exceptions
            if (!flag) {
                userInfoType.value = 'account'
            }
        }
    })
}
function changeMenu(item) {
    currentMenu.value = item.value
}
function handleLogout() {
    proxy.$confirm($t('message.confirm.exitLogin'), $t('message.prompt'), {
        confirmButtonText: $t('message.buttons.submit'),
        cancelButtonText: $t('message.buttons.cancal'),
        type: 'warning'
    }).then(() => {
        userStore.LogOut().then(res => {
            knowStore.clearKnowledge()
            if (props.remove) props.remove()
            router.push('/login')
        })
    }).catch(() => { })
}
function changeTenant(item) {
    if (item.id == userStore.userInfo.tenantId) return
    userStore.refreshToken(item.id).then(data => {
        if (data) {
            if (data.userDto && data.userDto.callBackUrl && localStorage.getItem('loginQuery')) {
                proxy.$openUrl(`${data.userDto.callBackUrl}?access_token=${data.access_token}&refresh_token=${data.refresh_token}`, '_self') // 'Bearer ' +
                localStorage.setItem('loginQuery', '')
            } else {
                // todo 清空历史消息
                // this.$store.dispatch('MESSAGE_SET_VAL',{
                //     remainingCount:0
                // })
                userStore.batchSetStore(data)
                userStore.setTenantInfo(data.userDto.tenant)
                userStore.setTenantId(data.userDto.tenantId)
                userStore.setUserInfo(data.userDto)
                if (route.path != '/index') {
                    router.push("/index")
                    setTimeout(() => {
                        location.reload()
                    }, 1000 * 0.1)
                } else {
                    location.reload()
                }
            }
        }
    })
}
function editRealName() {
    editNameShow.value = true
    nextTick(() => {
        editName.value.focus()
    })
}
function realNameEdit() {
    editNameShow.value = false
}
function headImgRemove(file, fileList) {
    imgFileList.value = fileList
    userdata.value.headImg = ''
}
function headImgSuccessHandle(res, file, fileList) {
    if (res.code == 0) {
        userdata.value.headImg = res.data.fileLink
        imgFileList.value = [{
            url: res.data.fileLink
        }]
        proxy.$notify({
            title: $t('message.prompt'),
            message: $t('message.message.uploadAvatar'),
            type: 'success',
            position: 'bottom-right'
        });
    } else {
        headImgUpload.clearFiles()
        proxy.$notify({
            title: $t('message.prompt'),
            message: (res.msg),
            type: 'error',
            position: 'bottom-right'
        });
    }
}
// 刷新token
function freshToken() {
    userStore.refreshToken(userStore.tenantId).then(res => {
        window.parent.postMessage({ command: 'fresh' }, '*')
    }).catch(() => {
        userStore.LogOut().then(() => {
            // sessionStorage.setItem('lastUrl', lastUrl)
            router.push({ path: "/login" });
            window.parent.postMessage({ command: 'loginOut' }, '*')
        });
    })
}
function headImgErrHandle(err, file, fileList) {
    headImgUpload.clearFiles()
    proxy.$notify({
        title: $t('message.prompt'),
        message: (err),
        type: 'error',
        position: 'bottom-right'
    });
}
function bindStatusChange(item) {
    if (exceptions.value[item.props]) {
        let func: any = null
        let str: String = ''
        switch (item.props) {
            case 'WECHAT_MP':
                str = $t('message.confirm.unBindWeChat')
                func = unbindWX
                break;
            case 'WX_ENTERPRISE':
                str = $t('message.confirm.unBindWeCom')
                func = unbindQW
                break;
            case 'Ding':
                str = $t('message.confirm.unBindDingTalk')
                func = unbindDD
                break;
            case 'LDAP':
                str = $t('message.confirm.unBindLDAP')
                func = unbindLDAP
                break;
            default:
                break;
        }
        allUnBind(str, func, item.label)
    } else {
        if (item.props == 'Ding') {
            getDDCode()
        } else if (item.props == 'WECHAT_MP') {
            getOffLoginQcodeF()
        }
        bindItem = item
        bindVisible.value = true
    }
}
function allUnBind(str: String, func: Function, label: String) {
    proxy.$confirm(str, $t('message.prompt'), {
        confirmButtonText: $t('message.buttons.submit'),
        cancelButtonText: $t('message.buttons.cancal'),
        type: 'warning'
    }).then(() => {
        if (func) {
            func().then((res: any) => {
                if (res.data.code == 0) {
                    proxy.$notify({
                        title: $t('message.prompt'),
                        message: $t('message.message.unBindSuccess') + label,
                        type: 'success',
                        position: 'bottom-right'
                    });
                    handleSetting(true)
                    freshToken()
                }
            })
        }
    }).catch(() => { })
}
function bindOrNext(type: String) {
    let str = $t('message.confirm.unBindPhone')
    let func = unbindPhone
    let label = $t('message.phone')
    let isBind: Boolean = !!phoneYzm.value.phone
    if (type == 'email') {
        func = unbindEmail
        str = $t('message.confirm.unBindEmail')
        label = $t('message.email')
        isBind = !!emailYzm.value.email
    }
    if (!isBind) {
        if (type == 'phone' && phoneYzm.value.value) {
            phoneYzm.value.step = 2
        } else if (emailYzm.value.value) {
            emailYzm.value.step = 2
        }
    } else {
        allUnBind(str, func, label)
    }
}
function submitPwd() {
    if (pwd.value == pwds.value) {
        let obj = {
            password: pwd.value,
            rePassword: pwds.value
        }
        let temp = encryption({
            data: obj,
            key: enCodePasswordKey, // enCodePasswordKey,
            param: ["password"]
        });
        temp = encryption({
            data: temp,
            key: enCodePasswordKey, // enCodePasswordKey,
            param: ["rePassword"]
        });
        setPassWord(temp).then(res => {
            if (res.data.code == 0) {
                proxy.$notify({
                    title: $t('message.prompt'),
                    message: $t('message.message.passwordSuccess'),
                    type: 'success',
                    position: 'bottom-right'
                });
                removeItemAll(['lib', 'allType', 'iconList', 'isMobile'])
                if (props.remove) props.remove()
                router.push('/mobile/login')
            }
        }).catch(() => { })
    } else {
        proxy.$msgbox({
            message: $t('message.message.passwordInconsistent'),
            title: $t('message.prompt'),
            type: 'warning',
            closeOnClickModal: false,
            confirmButtonText: $t('message.buttons.submit')
        })
    }
}
function cancalPwd() {
    pwd.value = ''
    pwds.value = ''
}
function saveUserInfo() {
    editUser(Object.assign({}, userdata.value, { sex: null })).then(res => {
        if (res.data.code == 0) {
            proxy.$notify({
                title: $t('message.prompt'),
                message: $t('message.message.saveInfoSuccess'),
                type: 'success',
                position: 'bottom-right'
            });
            freshToken()
        }
    })
}
function sendYzm(type: string) {
    if (type == 'phone') {
        if (phoneYzm.value.disabled) return
        phoneYzmInterval.value = setInterval(() => {
            phoneYzm.value.time -= 1
            phoneYzm.value.text = phoneYzm.value.time + `s${$t('message.login.resend')}`
            phoneYzm.value.disabled = true
            if (phoneYzm.value.time == 0) {
                clearInterval(phoneYzmInterval.value)
                phoneYzm.value.time = 180
                phoneYzm.value.text = $t('message.login.getVeriCode')
                phoneYzm.value.disabled = false
            }
        }, 1000)
        sendPhoneCode(phoneYzm.value.value).then(res => { }).catch(err => {
            if (phoneYzmInterval.value) {
                clearInterval(phoneYzmInterval.value)
            }
            phoneYzm.value.time = 180
            phoneYzm.value.text = $t('message.login.getVeriCode')
            phoneYzm.value.disabled = false
        })
    } else {
        if (emailYzm.value.disabled) return
        emailYzmInterval.value = setInterval(() => {
            emailYzm.value.time -= 1
            emailYzm.value.text = emailYzm.value.time + `s${$t('message.login.resend')}`
            emailYzm.value.disabled = true
            if (emailYzm.value.time == 0) {
                clearInterval(emailYzmInterval.value)
                emailYzm.value.time = 180
                emailYzm.value.text = $t('message.login.getVeriCode')
                emailYzm.value.disabled = false
            }
        }, 1000)
        sendEmailCode({ email: emailYzm.value.value }).then(res => { }).catch(err => {
            if (emailYzmInterval.value) {
                clearInterval(emailYzmInterval.value)
            }
            emailYzm.value.time = 180
            emailYzm.value.text = $t('message.login.getVeriCode')
        })
    }
}
function handleBindClose() {
    if (QRCheckSetInterval.value) {
        clearInterval(QRCheckSetInterval.value)
    }
    bindVisible.value = false
}
// 刷新二维码
function freshWeixin() {
    getOffLoginQcodeF()
}
// 获取微信公众号二维码
function getOffLoginQcodeF() {
    let uuid = getUUId(), uuidNew = []
    uuid.split('').forEach(item => {
        if (item != '-') {
            uuidNew.push(item)
        }
    });
    QRcodeUUId.value = uuidNew.join('')
    getOffLoginQcode(QRcodeUUId.value).then(res => {
        if (res.data.code == 0) {
            OfficQrcodeUrl.value = res.data.data
            isExpires.value = false
            startCheckState()
        }
    })
}
function getUUId() {
    return URL.createObjectURL(new Blob()).substr(-36)
}
function startCheckState() {
    if (QRCheckSetInterval.value) {
        clearInterval(QRCheckSetInterval.value)
    }
    QRCheckSetInterval.value = setInterval(() => {
        checkQrcodeState(QRcodeUUId.value).then(res => {
            if (res.data.code == 0 && res.data.data.checkStatus) {
                if (QRCheckSetInterval.value) {
                    clearInterval(QRCheckSetInterval.value)
                }
                let tp = {
                    data: JSON.stringify({ id: QRcodeUUId.value })
                }
                let temp = encryption({
                    data: tp,
                    key: enCodeKey,
                    param: ["data"]
                })
                bindWX({ code: temp.data, appId: client_id }).then(res => {
                    if (res.data.code == 0) {
                        proxy.$notify({
                            title: $t('message.prompt'),
                            message: $t('message.message.bindWeChatSuccess'),
                            type: 'success',
                            position: 'bottom-right'
                        });
                        handleSetting(true)
                        freshToken()
                        handleBindClose()
                    } else {
                        OfficQrcodeUrl.value = ''
                        freshWeixin()
                    }
                }).catch(() => {
                    OfficQrcodeUrl.value = ''
                    freshWeixin()
                })
            } else if (res.data.code == 0 && res.data.data.isPastDue) {
                isExpires.value = true
                if (QRCheckSetInterval.value) {
                    clearInterval(QRCheckSetInterval.value)
                }
            }
        })
    }, 1000 * 2)
}
/**
 * data 判定值
 * checkData 检验的值
 * isAll 是否包含所有的条件
 */
function hasLoginRight(data: never, checkData: never, isAll = false) {
    if (typeof data == 'object') {
        if (typeof checkData == 'object') {
            let sum = 0
            checkData.forEach((itemd: never) => {
                if (data.indexOf(itemd) != -1) {
                    sum++
                }
            })
            if (isAll) {
                return sum == checkData.length()
            } else {
                return !!sum
            }
        } else {
            return data.indexOf(checkData) != -1
        }
    } else {
        if (typeof checkData == 'object') {
            return checkData.indexOf(data) != -1
        } else {
            return checkData == data
        }
    }
}
// 钉钉二维码生成
function getDDCode() {
    getInfoByLoginType({ type: 'dd' }).then(res => {
        if (res && res.data && res.data.code == 0) {
            ddInfo.value = res.data.data
            let url = encodeURIComponent(`${location.origin}/#/login/dingtalk/bindback`);
            let goto = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${res.data.data.appId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`)
            ddCodeUrl.value = `https://login.dingtalk.com/login/qrcode.htm?goto=${goto}&style=border:none;background-color:#FFFFFF;`
        }
    })
}
// 钉钉扫码回调
function dingdingBackHandle(event: any) {
    var origin = event.origin;
    if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
        var loginTmpCode = event.data;
        //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        let url = encodeURIComponent(`${location.origin}/#/login/dingtalk/bindback`);
        let goto = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${ddInfo.value.appId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`)
        proxy.$openUrl(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${ddInfo.value.appId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${goto}&loginTmpCode=${loginTmpCode}`, '_self')
    }
}
function bindLADP(formItem: any) {
    formItem.validate((valid: any) => {
        if (valid) {
            let userInfo = JSON.parse(JSON.stringify(ldapForm))
            let tp = {
                data: JSON.stringify(userInfo)
            }
            let temp = encryption({
                data: tp,
                key: enCodeKey,
                param: ["data"]
            })
            bindLDAP({ code: temp.data, appId: client_id }).then(res => {
                if (res.data.code == 0) {
                    proxy.$notify({
                        title: $t('message.prompt'),
                        message: $t('message.message.bindLDAPSuccess'),
                        type: 'success',
                        position: 'bottom-right'
                    });
                    handleSetting(true)
                    freshToken()
                    handleBindClose()
                }
            }).catch(() => {
            })
        }
    })
}
function bindInputChange(type: String) {
    if (type == 'phone') {
        if (!phoneYzm.value.value) {
            phoneYzm.value.step = 1
        }
    } else {
        if (!emailYzm.value.value) {
            emailYzm.value.step = 1
        }
    }
}
function resetYzm(types: Array<String> = ['phone', 'email']) {
    if (phoneYzmInterval.value && types.indexOf('phone') != -1) {
        clearInterval(phoneYzmInterval.value)
    }
    if (emailYzmInterval.value && types.indexOf('email') != -1) {
        clearInterval(emailYzmInterval.value)
    }
    if (types.indexOf('phone') != -1) {
        phoneYzm.value = {
            step: 1,
            text: $t('message.login.getVeriCode'),
            phone: '',
            value: '',
            yzm: '',
            time: 180,
            disabled: false
        }
    }
    if (types.indexOf('email') != -1) {
        emailYzm.value = {
            step: 1,
            text: $t('message.login.getVeriCode'),
            email: '',
            yzm: '',
            value: '',
            time: 180,
            disabled: false
        }
    }

}
function bindPhoneOrEmail(type: String) {
    let obj: any = {
        email: emailYzm.value.value,
        code: emailYzm.value.yzm
    }, func = bindEmail, str = $t('message.message.bindEmailSuccess')
    if (type == 'phone') {
        func = bindPhone
        str = $t('message.message.bindPhoneSuccess')
        obj = {
            phone: phoneYzm.value.value,
            code: phoneYzm.value.yzm
        }
    }
    func(obj).then(res => {
        if (res.data.code == 0) {
            proxy.$notify({
                title: $t('message.prompt'),
                message: str,
                type: 'success',
                position: 'bottom-right'
            });
            handleSetting(true)
            freshToken()
        }
    })
}
function cancalUnBind(type: String) {
    resetYzm([type])
}
</script>
<style lang="scss">
.userInfo-modal {
    background-color: transparent !important;

    .el-drawer {
        box-shadow: -5px 0px 10px 0px rgba(54, 59, 76, 0.1) !important;

        .el-drawer__header {
            margin-bottom: 24px;
            padding: 24px 24px 0px;
            box-sizing: border-box;
        }

        .el-drawer__body {
            padding: 0px !important;
            box-sizing: border-box;
        }

        .account-title {
            .back {
                width: 20px;
                height: 20px;
                cursor: pointer;
            }

            .line {
                height: 10px;
                width: 1px;
                background-color: #6f7588;
                margin: 0px 8px;
            }

            display: flex;
            align-items: center;
        }

        .userInfo-title {
            font-size: 20px;
            color: #363B4c;
            @include SourceHanSansCN-Bold;
        }

        .userInfo-close {
            width: 16px;
            height: 16px;
            cursor: pointer;
            color: #575E73;
        }

        .user-info-body {
            .user-info-box {
                height: 104px;
                padding: 24px !important;
                box-sizing: border-box;
                position: relative;
                display: flex;
                align-items: center;

                .user-info-bg {
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    background-image: url('@/assets/images/userInfoBg.png');
                    left: 0px;
                    top: 0px;
                    z-index: 0;
                }

                .header-img {
                    min-width: 56px;
                    min-height: 56px;
                    width: 56px;
                    height: 56px;
                    border-radius: 10px;
                    overflow: hidden;
                }

                .info {
                    margin-left: 16px;
                    overflow: hidden;
                    z-index: 1;

                    .user-tenant-name {
                        color: #363B4C;
                        font-size: 16px;
                        @include SourceHanSansCN-Bold;
                        margin-bottom: 4px;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        overflow: hidden;
                    }

                    .user-name {
                        color: #363B4C;
                        font-size: 14px;
                        @include SourceHanSansCN-Regular;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        overflow: hidden;
                    }
                }
            }

            .seeting-logout-box {
                padding: 0px 24px;
                margin-top: 8px;
                margin-bottom: 24px;
                display: flex;

                .button {
                    padding: 16px;
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    width: 150px;
                    height: 48px;
                    border-radius: 6px;
                    background-color: #f5f6f7;
                    cursor: pointer;
                    color: #363B4C;
                    font-size: 14px;
                    @include SourceHanSansCN-Regular;

                    &:hover {
                        background-color: #EEEFF0;
                    }
                }

                .button+.button {
                    margin-left: 16px;
                }
            }

            .tenant-box {
                padding: 0px 24px 24px;
                box-sizing: border-box;

                .tenant-title {
                    color: #3D3D3D;
                    font-size: 16px;
                    @include SourceHanSansCN-Bold;
                }

                .tenant-body {
                    margin-top: 8px;
                    background: #F5F6F7;
                    border-radius: 6px 6px 6px 6px;
                    padding: 12px 0px;
                    box-sizing: border-box;
                    max-height: calc(100vh - 316px);
                    position: relative;
                    height: 100%;

                    .tenant-lists {
                        height: 100%;
                        max-height: calc(100vh - 336px);

                        .tenant-item {
                            padding: 12px 8px;
                            margin: 0px 8px;
                            box-sizing: border-box;
                            height: 64px;
                            display: flex;
                            border-radius: 6px;
                            align-items: center;
                            cursor: pointer;

                            .tenant-name {
                                @include SourceHanSansCN-Regular;
                                font-size: 14px;
                                color: #363B4c;
                                width: calc(100% - 76px);
                                text-overflow: ellipsis;
                                white-space: nowrap;
                                overflow: hidden;
                                margin-right: 4px;
                            }

                            .tenant-img {
                                min-width: 40px;
                                width: 40px;
                                height: 40px;
                                border-radius: 6px;
                                overflow: hidden;
                                margin-right: 16px;
                            }

                            .tenant-check {
                                width: 16px;
                                height: 16px;

                                .check-icon {
                                    width: 16px;
                                    height: 16px;
                                }
                            }

                            &:hover {
                                background: #EEEFF0;
                            }
                        }
                    }

                    .active {
                        background-color: #e4edff !important;
                    }
                }
            }
        }

        .account-set-body {
            display: flex;
            height: 100%;
            width: 100%;

            .account-menu-box {
                width: 168px;
                background: #F5F6F7;
                padding: 23px 8px;
                box-sizing: border-box;

                .menu-item {
                    height: 36px;
                    border-radius: 4px 4px 4px 4px;
                    color: #363B4C;
                    font-size: 14px;
                    @include SourceHanSansCN-Regular;
                    display: flex;
                    align-items: center;
                    padding-left: 18px;
                    box-sizing: border-box;
                    cursor: pointer;

                    .icon {
                        width: 16px;
                        height: 16px;
                        margin-right: 9px;
                    }

                    &:hover {
                        background: #EEEFF0;
                    }
                }

                .menu-item+.menu-item {
                    margin-top: 16px;
                }

                .menu-item-active {
                    background: #DDEAFF !important;
                    color: #1E6FFF;
                }
            }

            .menu-item-info-box {
                width: calc(100% - 168px);
                height: 100%;
                overflow: auto;
                padding: 24px;
                box-sizing: border-box;

                .user-box {
                    .user-item {
                        display: flex;
                        align-items: center;
                        margin: 16px 0px;

                        .user-item-name {
                            width: 64px;
                            font-size: 14px;
                            color: #6f7588;
                            @include SourceHanSansCN-Regular;
                        }

                        .user-item-content {
                            margin-left: 32px;
                            font-size: 14px;
                            color: #363B4C;
                            @include SourceHanSansCN-Regular;
                            display: flex;
                            align-items: center;

                            .avatar-uploader {
                                cursor: pointer;
                                overflow: hidden;
                                transition: var(--el-transition-duration-fast);

                                .avatar-uploader-icon {
                                    border: 1px dashed var(--el-border-color);
                                    border-radius: 6px;
                                    font-size: 28px;
                                    color: #8c939d;
                                    width: 56px;
                                    height: 56px;
                                    text-align: center;
                                }

                                .avatar {
                                    width: 56px;
                                    height: 56px;
                                    border-radius: 10px;
                                    overflow: hidden;
                                }
                            }

                            .el-input {
                                .el-input__wrapper {
                                    box-shadow: none !important;
                                    background: #F5F6F7 !important;
                                }
                            }

                            .edit-name-icon {
                                width: 16px;
                                height: 16px;
                                cursor: pointer;
                                margin-left: 8px
                            }
                        }
                    }

                    .submit-button {
                        margin-top: 16px;
                    }
                }

                .password-box {
                    .pwd-input {
                        width: 320px;
                        height: 36px;
                        margin-top: 12px;
                        background: #F5F6F7;
                        border-radius: 6px 6px 6px 6px;

                        .el-input__wrapper {
                            background-color: transparent !important;
                            box-shadow: none !important;
                        }
                    }

                    .tips {
                        color: #363B4C;
                        font-size: 14px;
                        margin-top: 16px;
                        margin-bottom: 4px;
                        @include SourceHanSansCN-Regular;
                    }

                    .buttons-box {
                        margin-top: 12px;

                        .cancal {
                            background: #F5F6F7;
                            border-color: #F5F6F7;
                            color: #494f6A;

                            &:hover {
                                background: #EEEFF0 !important;
                                border-color: #EEEFF0 !important;
                                color: #494f6A !important;
                            }
                        }
                    }
                }

                .account-box {
                    .s-title {
                        color: #363B4C;
                        @include SourceHanSansCN-Bold;
                        font-size: 14px;
                        margin-top: 24px;
                    }

                    .bind {
                        margin-top: 16px;
                        margin-bottom: 8px;

                        .title {
                            font-size: 14px;
                            color: #363B4C;
                            @include SourceHanSansCN-Regular;
                        }

                        .bind-input {
                            display: flex;
                            align-items: center;
                            margin-top: 8px;

                            .el-input {
                                height: 36px;
                                width: 320px;
                                margin-right: 16px;

                                .el-input__wrapper {
                                    box-shadow: none !important;
                                    background: #F5F6F7 !important;
                                }
                            }

                            button {
                                height: 36px;
                                @include SourceHanSansCN-Regular;
                            }

                            .unbind {
                                background: #F5F6F7;
                                border-radius: 6px;
                                border-color: #F5F6F7;
                                color: #1E6FFF;
                                font-size: 14px;

                                &:hover {
                                    background: #EEEFF0;
                                    border-color: #EEEFF0;
                                }
                            }

                            .send-button {
                                background: #F5F6F7;
                                border-radius: 6px;
                                border-color: #F5F6F7;
                                color: #1E6FFF;
                                font-size: 14px;
                                width: 102px;

                                &:hover {
                                    background: #EEEFF0;
                                    border-color: #EEEFF0;
                                }
                            }
                        }

                        .buttons-box {
                            margin-top: 12px;

                            .cancal {
                                background: #F5F6F7;
                                border-color: #F5F6F7;
                                color: #494f6A;

                                &:hover {
                                    background: #EEEFF0 !important;
                                    border-color: #EEEFF0 !important;
                                    color: #494f6A !important;
                                }
                            }
                        }

                        .bind-input+.bind-input {
                            margin-top: 12px;
                        }
                    }

                    .other-bind {
                        margin-top: 16px;

                        .other-item {
                            display: flex;
                            align-items: center;
                            @include SourceHanSansCN-Regular;

                            .other-icon {
                                width: 32px;
                                height: 32px;
                            }

                            .label {
                                margin-left: 16px;
                                width: 60px;
                                font-size: 14px;
                                color: #363B4C;
                            }

                            button {
                                margin-left: 32px;
                                background: #F5F6F7;
                                border-color: #F5F6F7;
                                color: #363B4C;

                                &:hover {
                                    color: #363B4C !important;
                                    background: #EEEFF0;
                                }
                            }

                            .binding {
                                color: #1E6FFF;

                                &:hover {
                                    color: #1E6FFF !important;
                                }
                            }
                        }

                        .other-item+.other-item {
                            margin-top: 16px;
                        }
                    }
                }

                .user-title {
                    color: #363B4C;
                    font-size: 16px;
                    @include SourceHanSansCN-Bold;
                }
            }
        }
    }
}

.account-modal {
    .el-drawer__body {
        border-top: 1px solid #EEEFF0;
    }
}

.bind-dialog {
    border-radius: 6px !important;
    height: 425px;
    top: 50%;
    transform: translateY(calc(-50% - 15vh));

    .el-dialog__header {
        display: flex;
        align-items: center;
        margin-right: 0px;
        padding: 16px 32px;
        justify-content: space-between;
        border-bottom: 1px solid #F5F6F7;

        .userInfo-close {
            width: 16px;
            height: 16px;
            cursor: pointer;
            color: #575E73;
        }

        .bind-title {
            color: #363B4C;
            font-size: 16px;
            @include SourceHanSansCN-Bold;
        }
    }

    .bind-body {
        .qcode-box {
            // width: 220px;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 32px;

            .qcode-title {
                font-size: 20px;
                @include SourceHanSansCN-Regular;
                color: #363B4C;
                text-align: center;
            }

            .qcode-tips {
                @include SourceHanSansCN-Regular;
                font-size: 14px;
                color: #6F7588;
                text-align: center;
                margin-top: 6px;
            }

            .qcode-body-box {
                width: 220px;
                height: 220px;
                position: relative;
                margin-top: 16px;

                img {
                    width: 100%;
                    cursor: pointer;
                }

                .qcode-mark {
                    position: absolute;
                    z-index: 2;
                    top: 0px;
                    left: 0px;
                    background: transparent;
                    width: 220px;
                    height: 220px;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: rgba(255, 255, 255, 0.8);

                    .tips {
                        @include SourceHanSansCN-Regular;
                        font-size: 14px;
                    }
                }

                .iframe-box {
                    width: 220px;
                    height: 230px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    overflow: hidden;
                    position: relative;
                    margin-top: 10px;
                    box-sizing: border-box;

                    .dd-box {
                        position: absolute;
                        width: 210px;
                        height: 250px;
                        top: -40px;
                    }

                    .wxenter-box {
                        position: absolute;
                        width: 220px;
                        height: 260px;
                        top: -44px;
                    }
                }
            }

            .ldap-box {
                width: 100%;
                padding: 0px 12px;
                box-sizing: border-box;

                .el-input {
                    height: 36px;
                    margin-bottom: 2px;

                    .el-input__wrapper {
                        box-shadow: none !important;
                        background-color: #F5F6F7 !important;
                    }
                }

            }
        }
    }
}

.LDAP-dialog {
    height: 321px;

    .el-dialog__body {
        padding-top: 20px !important;
        padding-bottom: 10px !important;
    }

    .el-dialog__footer {
        border-top: 1px solid #EEEFF0;
        padding: 16px 16px 12px;
    }

    .qcode-box {
        margin-bottom: 0px !important;

        .button-box {
            text-align: right;

            .cancal {
                background: #F5F6F7;
                border-color: #F5F6F7;
                color: #494f6A;

                &:hover {
                    background: #EEEFF0 !important;
                    border-color: #EEEFF0 !important;
                    color: #494f6A !important;
                }
            }
        }
    }
}
</style>
